<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          @click="handleAdd"
          v-if="sdPermissions.includes('sys:dept:save')"
          >新增</el-button
        >
      </div>
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column label="名称" align="left">
          <template slot-scope="scope">
            <div @click="handleRow(scope.$index, scope.row)">
              <span class="space" v-for="i in scope.row.level" :key="i"></span>
              <i
                :class="{
                  'el-icon-caret-right': !scope.row.show,
                  'el-icon-caret-bottom': scope.row.show
                }"
                v-if="scope.row.children && scope.row.children.length"
              ></i>
              <span class="arrow-width" v-else></span>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="parentName" align="center" label="上级部门">
        </el-table-column>
        <el-table-column prop="sort" align="center" label="排序">
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="sdPermissions.includes('sys:dept:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="sdPermissions.includes('sys:dept:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="50%">
      <el-form ref="addForm" :model="addForm" label-width="auto" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="deptName"></el-input>
        </el-form-item>
        <el-form-item label="上级部门" prop="parentName">
          <div class="block">
            <el-cascader
              :options="addForm.options"
              :props="{ checkStrictly: true }"
              clearable
              @change="valueChange"
              v-model="deptvalue"
              ref="cascader"
            ></el-cascader>
          </div>
        </el-form-item>

        <el-form-item label="排序">
          <template>
            <el-input-number
              v-model="addForm.sort"
              @change="handleChange"
              :min="0"
              :max="Infinity"
              label="描述文字"
            ></el-input-number>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
      <el-form ref="editForm" :model="editForm" label-width="auto">
        <el-form-item label="名称" prop="name">
          <el-input v-model="deptName"></el-input>
        </el-form-item>
        <el-form-item label="上级部门" prop="parentName">
          <div class="block">
            <el-cascader
              :options="editForm.options"
              :props="{ checkStrictly: true }"
              clearable
              @change="valueChange"
              v-model="deptvalue"
              ref="cascader"
            ></el-cascader>
          </div>
        </el-form-item>

        <el-form-item label="排序">
          <template>
            <el-input-number
              v-model="editForm.sort"
              @change="handleChange"
              :min="0"
              :max="Infinity"
              label="描述文字"
            ></el-input-number>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import { sysDeptMixin } from "common/js/userManage";
import util from "utils/util";
import { mapGetters } from "vuex";
// console.log(sysDeptMixin);
export default {
  // mixins: [sysDeptMixin],
  data() {
    return {
      sdPermissions: [],
      deptName: "",
      deptvalue: [],
      editVisible: false,
      addVisible: false,
      rules: {
        name: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        parentName: [
          { required: false, message: "必填不能为空", trigger: "blur" }
        ]
      },
      editForm: {
        id: "",
        pid: "",
        children: [],
        name: "",
        sort: 0,
        createDate: null,
        parentName: null,
        options: [
          {
            value: "",
            label: "",
            children: []
          }
        ]
      },
      addForm: {
        name: "",
        parentName: "",
        sort: 0,
        pid: "",
        options: [
          {
            value: "",
            label: "",
            children: []
          }
        ]
      },
      tableData: [
        {
          id: 1,
          pid: "0",
          name: "",
          sort: 1,
          parentName: null,
          createDate: null,
          show: false,
          children: []
        }
      ],
      ids: []
    };
  },

  created() {
    // 获取数据
    this.getJSData({});
    this.sdPermissions = this.permissions;
  },
  // computed: {
  //   ...mapGetters(["permissions"])
  // },
  computed: {
    ...mapGetters(["permissions"])
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/sys-dept") {
        this.sdPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      this.sdPermissions = newVal;
    },
    deptvalue() {
      if (this.$refs.cascader) {
        this.$refs.cascader.dropDownVisible = false;
      }
    }
  },

  methods: {
    getJSData({ order = "", orderField = "", _t = Date.now() }) {
      this.$axios
        .get("/sys/dept/list", {
          params: {
            order,
            orderField,
            _t
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          function myMap(array) {
            array.map(item => {
              item.show = false;
              if (item.children && item.children.length) {
                return myMap(item.children);
              }
            });
          }
          myMap(res.data);
          this.tableData = res.data;
          this.tableData.map(item => {
            item.show = false;
            item.level = 0;
            if (item.children && item.children.length) {
              item.children.map(subItem => {
                subItem.show = false;
                subItem.level = 1;
                if (subItem.children && subItem.children.length) {
                  subItem.children.map(grandsonItem => {
                    grandsonItem.show = false;
                    grandsonItem.level = 2;
                  });
                }
              });
            }
          });
          console.log("部门管理", this.tableData);
        })
        .catch(() => {});
    },
    // 上级部门 根据name找到父级id 设置给子级的pid
    valueChange(value) {
      console.log(value);
      if (this.addVisible) {
        value = value[value.length - 1];
        this.addForm.parentName = value;

        function myMap(array, name) {
          var arr = array.map(item => {
            if (item.name === name) {
              return item.id;
            } else {
              if (item.children && item.children.length) {
                return myMap(item.children, name);
              }
            }
          });
          return arr;
        }
        var result = myMap(this.addForm.options, value);
        var str = "";
        function recursion(array) {
          for (var item of array) {
            if (item === undefined) {
              continue;
            } else if (
              item !== undefined &&
              Object.prototype.toString.call(item) === "[object Array]"
            ) {
              recursion(item);
            } else {
              str = item;
            }
          }
        }
        recursion(result);
        this.addForm.pid = str;
      } else if (this.editVisible) {
        value = value[value.length - 1];
        this.editForm.parentName = value;
        // 根据name找到父级id 设置给子级的pid
        function myMap(array, name) {
          var arr = array.map(item => {
            if (item.name === name) {
              return item.id;
            } else {
              if (item.children && item.children.length) {
                return myMap(item.children, name);
              }
            }
          });
          return arr;
        }
        var result = myMap(this.editForm.options, value);
        var str = "";
        function recursion(array) {
          for (var item of array) {
            if (item === undefined) {
              continue;
            } else if (
              item !== undefined &&
              Object.prototype.toString.call(item) === "[object Array]"
            ) {
              recursion(item);
            } else {
              str = item;
            }
          }
        }
        recursion(result);
        this.editForm.pid = str;
      }
    },
    // 排序
    handleChange(currentValue, oldValue) {
      // console.log(currentValue, oldValue);
      if (this.addVisible) {
        this.addForm.sort = currentValue;
      } else if (this.editVisible) {
        this.editForm.sort = currentValue;
      }
    },
    saveAdd() {
      // 得到成功提示
      this.$axios
        .post("/sys/dept", {
          name: this.deptName,
          pid: this.addForm.pid || "0", // 找到pid
          parentName: this.addForm.parentName,
          sort: this.addForm.sort,
          children: [],
          createDate: null
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success("操作成功");
          this.addVisible = false;
          this.addForm = {};
          this.deptName = "";
          this.getJSData({});
        })
        .catch(() => {});
    },

    // 递归思想: 添加label属性
    addLabelAttribute(arr) {
      for (var i = 0; i < arr.length; i++) {
        if ("children" in arr[i] && arr[i].children.length !== 0) {
          arr[i].label = arr[i].name;
          arr[i].value = arr[i].name;
          this.addLabelAttribute(arr[i].children);
        } else if ("children" in arr[i] && arr[i].children.length === 0) {
          arr[i].label = arr[i].name;
          arr[i].value = arr[i].name;
          delete arr[i].children;
        } else if (!("children" in arr[i])) {
          arr[i].label = arr[i].name;
          arr[i].value = arr[i].name;
        }
      }
    },
    // 保存编辑
    saveEdit() {
      // 得到成功提示
      this.$axios
        .put("/sys/dept", {
          id: this.editForm.id,
          name: this.deptName,
          pid: this.editForm.pid,
          parentName: this.editForm.parentName,
          sort: this.editForm.sort,
          children: this.editForm.children,
          createDate: this.editForm.createDate
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success("操作成功");
          this.editVisible = false;

          this.getJSData({});
        })
        .catch(() => {});
    },
    // 编辑操作
    handleEdit(index, row) {
      // console.log(index, row);
      this.idx = index;
      this.editVisible = true;

      // 初始化上级部门  editForm.options: []
      this.initParaentDept();
      // 初始化编辑表单页面
      this.$axios
        .get("/sys/dept/" + row.id, {
          _t: Date.now()
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          for (var key in res.data) {
            this.editForm[key] = res.data[key];
          }

          this.deptvalue = [];
          this.deptName = this.editForm.name;
          this.deptvalue.push(this.editForm.parentName);
        })
        .catch(() => {});
    },
    // 新增
    handleAdd() {
      this.deptName = "";
      this.deptvalue = [];
      this.addVisible = true;
      // 初始化上级部门
      this.initParaentDept();
    },
    initParaentDept() {
      this.$axios
        .get("/sys/dept/list", {
          params: {
            _t: Date.now()
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }

          if (this.addVisible) {
            this.addLabelAttribute(res.data);
            this.addForm.options = res.data;
            console.log(this.addForm.options);
          } else if (this.editVisible) {
            this.addLabelAttribute(res.data);
            this.editForm.options = res.data;
          }
          console.log(this.editForm);
        })
        .catch(() => {});
    },

    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.singleDelete.call(
        this,
        "/sys/dept/",
        index,
        this.ids,
        this.getJSData
      );
    },
    handleRow(index, row) {
      index++;
      if (row.children && row.children.length > 0) {
        if (row.show) {
          row.show = false;
          var length = row.children.length;
          function myMap(array) {
            array.map(item => {
              if (item.show) {
                item.show = false;
                length += item.children.length;
                return myMap(item.children);
              }
            });
          }
          myMap(row.children);
          this.tableData.splice(index, length);
        } else {
          row.children.forEach(value => {
            this.tableData.splice(index, 0, value);
            index++;
          });
          row.show = true;
        }
      }
    }
  }
};
</script>
<style lang="scss">
@import "../../common/css/base.css";
</style>
